<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form v-if="tabsKeys == 1" size="small" :model="pageData" layout="inline">
            <a-form-item label="单号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" v-model="pageData.z"/>
            </a-form-item>
            <CorporateSectorCascader :configCascader="configCascader3" @changeCascader="changeCascader3"/>
            <a-form-item label="仓库">
              <a-select popup-container="html" class="bacClass" :style="{ width: '10rem' }" v-model="pageData.b"
                        allow-clear>
                <a-option v-for="item in fhWhList3" :value="item.id">
                  {{ item.warehouseName }}
                </a-option>
              </a-select>
            </a-form-item>
            <!-- <a-form-item label="出库类型">
                <a-select popup-container="html"  v-if="tabsKeys == 1" :style="{ width: '200px' }" class="bacClass" v-model="pageData.f"
                    allow-clear>
                    <a-option :value="1">领料单出库</a-option>
                    <a-option :value="2">调拨单出库</a-option>
                </a-select>
                <a-select popup-container="html"  v-if="tabsKeys == 3" :style="{ width: '200px' }" class="bacClass" v-model="pageData.f"
                    allow-clear>
                    <a-option :value="3">采购退货</a-option>
                    <a-option :value="4">采购换货</a-option>
                </a-select>
            </a-form-item> -->
          </a-form>
          <a-form v-else-if="tabsKeys == 2" size="small" :model="pageData" layout="inline">
            <a-form-item label="领料单号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                       v-model="pageData.c"/>
            </a-form-item>
            <a-form-item label="物料编号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                       v-model="pageData.d"/>
            </a-form-item>
            <a-form-item label="物料名称">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                       v-model="pageData.e"/>
            </a-form-item>
          </a-form>
          <a-form v-else-if="tabsKeys == 3" size="small" :model="pageData" layout="inline">
            <a-form-item label="单号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" v-model="pageData.f"/>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar :items="toolbarList" @add="addList" @select="selectHandler" @add-db="adddbs" @del="delSles"
                   @audit="audits" @oders="redersOut" @dyBoufei="dyBoufeis" @print="printRef">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-tabs   :lazy-load="true" :justify="true" :default-active-key="tabsKeys" @change="tabsChanges">
        <a-tab-pane title="已处理" :key="1">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                           rowSelection="multiple" @grid-ready="gridReady"
                           style="height: calc(100% - 45px)" :defaultColDef="defaultColDef" class='ag-theme-alpine'
                           :rowData="tableDataList"
                           :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
          <paginationCopys :page-size-options="pagingList1" :total="fySelet2.total" show-total show-jumper
                           show-page-size @change="PageSize2" @page-size-change="change2"
                           style="justify-content: center"
                           :page-size="fySelet2.size" :current="fySelet2.page"/>
        </a-tab-pane>
        <a-tab-pane title="领料单待处理" :key="2">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                           rowSelection="multiple" @grid-ready="gridReady2"
                           style="height: calc(100% - 45px)" :defaultColDef="defaultColDef2" class='ag-theme-alpine'
                           :rowData="tableDataList2"
                           :columnDefs="tc2" :localeText="localeText1"></AgGridVuesCopys>
          <paginationCopys :page-size-options="pagingList1" :total="fySelet.total" show-total show-jumper
                           show-page-size @change="PageSize" @page-size-change="change" style="justify-content: center"
                           :page-size="fySelet.size" :current="fySelet.page"/>
        </a-tab-pane>
        <a-tab-pane title="打印列表" :key="3">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                           rowSelection="multiple" @grid-ready="gridReady3"
                           style="height: calc(100% - 45px)" :defaultColDef="defaultColDef3" class='ag-theme-alpine'
                           :rowData="tableDataList3"
                           :columnDefs="tc3" :localeText="localeText1"></AgGridVuesCopys>
          <paginationCopys :page-size-options="pagingList1" :total="fySelet3.total" show-total show-jumper
                           show-page-size @change="PageSize3" @page-size-change="change3"
                           style="justify-content: center"
                           :page-size="fySelet3.size" :current="fySelet3.page"/>
        </a-tab-pane>
      </a-tabs>

    </template>
    <a-modal v-model:visible="cgOut.visible" :on-before-ok="cgHandleOk" @cancel="cadelvs" fullscreen
             :mask-closable="false">
      <template #title>
        {{ cgOut.title }}
      </template>
      <a-table :columns="cgColumns" :data="cgData" :pagination="false" :bordered="{ cell: true }">
        <template #oldNewNum="{ record }">
          <a-input-number v-model="record.oldNewNum" class="bacClass" :min="0" @change="NumChange(record)"
                          :disabled="pageData.isEdit" @mouseenter="numEnter(record)"/>
        </template>
      </a-table>
    </a-modal>
    <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 999 }" :mask-closable="false"
              unmount-on-close
              popup-container=".arco-tabs-content" :height="'90%'" :visible="dbPageDate.showAdd" @ok="sideOk"
              placement="bottom" @cancel="sideNo">
      <template #title>
        {{ dbPageDate.titles }}
      </template>
      <div style="min-width:1500px; overflow:auto;">
        <el-scrollbar>
          <a-form ref="formRef" layout="inline" :model="searchData" size="mini">
            <CorporateSectorCascader :configCascader="configCascader" @changeCascader="changeCascader"/>
            <a-form-item label="发货仓库" :rules="[{ required: true, message: '仓库必填' }]" field="fhWh">
              <a-select popup-container="html" class="bacClass" :style="{ width: '10rem' }" v-model="searchData.fhWh"
                        allow-clear>
                <a-option v-for="item in fhWhList" :value="item.id + '-' + item.warehouseName">
                  {{ item.warehouseName }}
                </a-option>
              </a-select>
            </a-form-item>
            <CorporateSectorCascader :configCascader="configCascader2" @changeCascader="changeCascader2"/>
            <a-form-item label="收货仓库类型" :rules="[{ required: true, message: '仓库必填' }]" field="shWhType">
              <a-select popup-container="html" class="bacClass" :style="{ width: '10rem' }" allow-search
                        v-model="searchData.shWhType" allow-clear @change="whTypeChanges">
                <a-option>五金仓</a-option>
                <a-option>制具仓</a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="收货仓库" :rules="[{ required: true, message: '仓库必填' }]" field="shWh">
              <a-select popup-container="html" class="bacClass" :style="{ width: '10rem' }" v-model="searchData.shWh"
                        allow-clear>
                <a-option v-for="item in shWhList" :value="item.id + '-' + item.warehouseName">
                  {{ item.warehouseName }}
                </a-option>
              </a-select>
            </a-form-item>

          </a-form>

          <a-space style="margin-bottom:10px;">
            <a-button type="primary" @click="addLine" size="mini">新增</a-button>
            <a-button type="primary" @click="delLine" size="mini">删除</a-button>
          </a-space>
          <a-table stripe :bordered="true" :columns="tableColumnsWl" size="mini" :data="wlListArray"
                   :row-selection="{ showCheckedAll: true, width: 50 }" rowKey="typeIds"
                   v-model:selected-keys="selectedRowKeysWl">
            <template #materialName="{ record }">
              <div style="width:100%;">
                <a-select popup-container="html" class="bacClass" :allowClear="true" v-model="record.materialName"
                          allow-search
                          @focus="focusSel2({ 'materialName': '' })"
                          @change="changeWl(record, record.materialName)">
                  <a-option v-for="item in wlPageDatas.wlList" :value="item['materialName']">{{
                      item['materialName']
                    }}
                  </a-option>
                </a-select>
              </div>
            </template>
            <template #materialCode="{ record }">
              <div style="width:100%;">
                <a-select popup-container="html" class="bacClass" :allowClear="true" v-model="record.materialCode"
                          allow-search
                          @focus="focusSel2({ 'materialCode': '' })"
                          @change="changeWl2(record, record.materialCode)">
                  <a-option v-for="item in wlPageDatas.wlList" :value="item['materialCode']">{{
                      item['materialCode']
                    }}
                  </a-option>
                </a-select>
              </div>
            </template>
            <template #totalNum="{ record }">
              <div style="width:100%;">
                <a-input-number v-model="record.totalNum" class="input-demo bacClass" :min="0"
                                :max="record.totalNum2"/>
              </div>
            </template>
            <template #grade="{ record }">
              <a-select popup-container="html" @click="gradeChange(record)" @change="grachanges(record)"
                        class="bacClass"
                        v-model="record.grade" allow-clear allow-search>
                <a-option v-for="item in gradrList">{{
                    item.detailName
                  }}
                </a-option>
              </a-select>
            </template>
          </a-table>
        </el-scrollbar>
      </div>
    </a-drawer>
    <a-modal v-model:visible="cgOut.visible2" :on-before-ok="cgHandleOk2" @cancel="cadelvs2" fullscreen
             :mask-closable="false">
      <template #title>
        调拨出库修改
      </template>
      <a-table :columns="cgColumns2" :data="cgData2" :pagination="false" :bordered="{ cell: true }">
        <template #totalNum="{ record }">
          <a-input-number class="bacClass" v-model="record.totalNum" :max="100000000" :min="0"></a-input-number>
        </template>
      </a-table>
    </a-modal>
    <a-drawer ok-text="保存" cancel-text='关闭' :drawer-style="{ 'zIndex': 999 }" :mask-closable="false"
              unmount-on-close
              popup-container=".arco-tabs-content" :height="'90%'" :visible="dbPageDate.showAdd2" @ok="sideOk2"
              placement="bottom" @cancel="sideNo2">
      <template #title>
        新增采购出库
      </template>
      <a-form ref="formRef2" size="mini" :model="searchData" layout="inline">
        <CorporateSectorCascader :configCascader="configCascader" @changeCascader="changeCascader"/>
        <a-form-item label="仓库" :rules="[{ required: true, message: '仓库必填' }]" field="fhWh">
          <a-select popup-container="html" class="bacClass" :style="{ width: '10rem' }" v-model="searchData.fhWh"
                    allow-clear>
            <a-option v-for="item in fhWhList" :value="item.id + '-' + item.warehouseName">
              {{ item.warehouseName }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="出库类型" :rules="[{ required: true, message: '出库类型必填' }]" field="infoType">
          <a-select popup-container="html" v-if="tabsKeys == 3" :style="{ width: '200px' }" class="bacClass"
                    v-model="searchData.infoType" allow-clear>
            <a-option :value="3">采购退货</a-option>
            <a-option :value="4">采购换货</a-option>
          </a-select>
        </a-form-item>
      </a-form>
      <a-space style="margin-bottom:10px;">
        <a-button type="primary" @click="addLine2" size="mini">新增</a-button>
      </a-space>
      <a-table :columns="cgColumns4" :data="cgData4" :pagination="false" :bordered="{ cell: true }">
        <template #totalNum="{ record }">
          <a-input-number class="bacClass" v-model="record.totalNum" :max="record.totalNum2"
                          :min="0"></a-input-number>
        </template>
        <template #acFighs="{ record }">
          <a-button type="primary" @click="delLine2(record)" size="mini">删除</a-button>
        </template>
      </a-table>
    </a-drawer>
    <a-modal fullscreen v-model:visible="visibleYl" :on-before-ok="handleOks" @cancel="handleCancels"
             :mask-closable="false">
      <template #title> 选择采购单</template>
      <div class="cgisDatas">
        <div>
          <span>物料编号:</span>
          <a-input class="bacClass" v-model="isLyCodeds" :style="{ width: '150px' }"
                   allow-clear/>
        </div>
        <div>
          <span>物料名称:</span>
          <a-input class="bacClass" v-model="isLyNameds" :style="{ width: '150px' }"
                   allow-clear/>
        </div>
        <a-button type="primary" size="mini" @click="cxCgsLists">查询</a-button>
      </div>
      <a-table :style="{
                height: '500px',
                marginTop: '10px',
            }" :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }" rowKey="typeLesIds"
               v-model:selected-keys="selectedRowKeys2" stripe :bordered="true" :scrollbar="true" sticky-header
               :pagination="false" :columns="cgColumns5" :data="wlListXqs">
      </a-table>
      <paginationCopys :page-size-options="pagingList1" :total="fySelet4.total" show-total show-jumper show-page-size
                       @change="PageSize4" @page-size-change="change4" style="justify-content: center"
                       :page-size="fySelet4.size"
                       :current="fySelet4.page"/>
    </a-modal>
    <a-modal ok-text="打印" :width="900" v-model:visible="visibleYl2" :on-before-ok="handleOks2"
             @cancel="handleCancels2">
      <template #title>五金出库单</template>
      <div id="wjDyings">
        <div class="No1">
          <div class="No1-1">肇庆市粤隆纺织有限公司</div>
          <div class="No1-2">五金出库单</div>
          <div class="No1-3">
            <div>出库单号:&nbsp;&nbsp;{{ printDatas?.orderNo }}</div>
            <!-- <div>供货单位:&nbsp;&nbsp;{{printDatas?.supplierName}}</div> -->
          </div>
          <div class="No1-4">
            <div>开单日期:&nbsp;&nbsp;{{ printDatas?.createTime }}</div>
            <div>出库类型:&nbsp;&nbsp;{{ printDatas?.outStockType }}</div>
            <div>收料人:</div>
          </div>
          <div class="No1-5">
            <div>备注:</div>
          </div>
        </div>
        <table class="isTable">
          <tr>
            <th>产品编号</th>
            <th>产品名称</th>
            <th>批次</th>
            <th>规格</th>
            <th>单位</th>
            <th>数量</th>
            <th>单价</th>
            <th>金额</th>
            <th>备注</th>
          </tr>
          <tr v-for="item in printDataLists">
            <td>{{ item.materialCode }}</td>
            <td>{{ item.materialName }}</td>
            <td>{{ item.grade }}</td>
            <td>{{ item.specification }}</td>
            <td>{{ item.unit }}</td>
            <td>{{ item.totalNum }}</td>
            <td>{{ item.price }}</td>
            <td></td>
            <td></td>
          </tr>
        </table>
      </div>
    </a-modal>
  </pageTabelLayout>
</template>
<script setup lang="ts">
import {ref} from "vue"
import {post, get} from "@/api/http"
import {localeText} from '@/api/aggridZw'

import Toolbar from "@/components/Toolbar.vue"
import {Message, Modal} from "@arco-design/web-vue"
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import printJS from 'print-js'
import WHService from "@/service/wh"
import {pagingList} from '@/api/paging'

const pagingList1: any = ref(pagingList)
// 新建调拨单
const toolbarList: any = ref(['查询', '审核', '删除'])

const fySelet: any = reactive({
  total: 10,
  size: 10,
  page: 1
})

const PageSize = (val: any) => {
  fySelet.page = val
  cxCgsList()
}

const change = (val: any) => {
  fySelet.size = val
  cxCgsList()
}

const fySelet2: any = reactive({
  total: 10,
  size: 10,
  page: 1
})

const PageSize2 = (val: any) => {
  fySelet2.page = val
  cxYcList()
}

const change2 = (val: any) => {
  fySelet2.size = val
  cxYcList()
}

const fySelet3: any = reactive({
  total: 10,
  size: 10,
  page: 1
})

const PageSize3 = (val: any) => {
  fySelet3.page = val
  cxYcList2()
}

const change3 = (val: any) => {
  fySelet3.size = val
  cxYcList2()
}

const fySelet4: any = reactive({
  total: 10,
  size: 10,
  page: 1
})

const PageSize4 = (val: any) => {
  fySelet4.page = val
  cxCgsLists()
}

const change4 = (val: any) => {
  fySelet4.size = val
  cxCgsLists()
}

const headerShow = ref(true)

const pageData: any = reactive({
  a: '',
  b: '',
  c: '',
  d: '',
  e: '',
  f: '',
  g: '',
  z: '',
  isEdit: false
})

const tableDataList = ref([])

const tableDataList2 = ref([])

const tableDataList3 = ref([])

const gridOption = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
}

const gridOption2 = ref()
const gridReady2 = (params: any) => {
  gridOption2.value = params.api
}

const gridOption3 = ref()
const gridReady3 = (params: any) => {
  gridOption3.value = params.api
}

const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
}

const defaultColDef2 = {
  sortable: true,
  resizable: true,
  filter: true,
}

const defaultColDef3 = {
  sortable: true,
  resizable: true,
  filter: true,
  flex: 1
}

const localeText1: any = ref(localeText)

const tc = [
  {
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {
    headerName: '单号',
    field: 'orderNo',
    // pinned: o['fixed'],
    width: 150
  },
  {
    headerName: '类型',
    field: 'infoType',
    width: 150,
    cellRenderer: {
      template: `<span>{{ states == 1 ? '领料出库' : states == 2 ? '调拨出库' : '' }}</span>`,
      setup(props: any) {
        return {
          states: props.params.data.infoType
        }
      }
    }
  },
  {
    headerName: '出库类型',
    field: 'outStockType',
    width: 150
  },
  {
    headerName: '公司',
    field: 'companyName',
    width: 150
  },
  {
    headerName: '仓库类别',
    field: 'warehouseTypeName',
    width: 150
  },
  {
    headerName: '仓库',
    field: 'warehouseName',
    width: 150
  },
  {
    headerName: '五金领料单号',
    field: 'materialRequestNo',
    width: 150
  },
  {
    headerName: '收货仓库类型',
    field: 'inWarehouseTypeName',
    width: 150
  },
  {
    headerName: '收货公司',
    field: 'inCompanyName',
    width: 150
  },
  {
    headerName: '收货仓库',
    field: 'inWarehouseName',
    width: 150
  },
  {
    headerName: '物料大类',
    field: 'majorCategory',
    width: 150
  },
  {
    headerName: '物料小类',
    field: 'subCategory',
    width: 150
  },
  {
    headerName: '物料编号',
    field: 'materialCode',
    width: 150
  },
  {
    headerName: '物料名称',
    field: 'materialName',
    width: 150
  },
  {
    headerName: '规格',
    field: 'specification',
    width: 150
  },
  {
    headerName: '出库数量',
    field: 'totalNum',
    width: 150
  },
  {
    headerName: '单位',
    field: 'unit',
    width: 150
  },
  {
    headerName: '状态',
    field: 'infoState',
    pinned: 'right',
    width: 190,
    cellRenderer: {
      template: `
        <a-button v-if="states == 2" status="success">已出库</a-button>
        <a-button v-if="states == 0" status="warning">待审核</a-button>
        <a-space v-if="states == 1">
          <a-button type="primary" status="danger" disabled>已驳回</a-button>
          <a-button type="primary" @click="a">修改</a-button>
        </a-space>
        <a-button v-if="states == 3">已完结</a-button>
      `,
      setup(props: any) {
        const a = () => {
          redersOut2(props.params.data)
        }
        return {
          a,
          states: props.params.data.infoState
        }
      }
    }
  }
]

const tc2 = [
  {
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {
    headerName: '领料单号',
    field: 'materialRequestNo',
    // pinned: o['fixed'],
    width: 150
  },
  {
    headerName: '公司',
    field: 'firm',
    // pinned: o['fixed'],
    width: 150
  },
  {
    headerName: '仓库名称',
    field: 'warehouseName',
    width: 150
  },
  // {
  //     headerName: '组名称',
  //     field: 'department',
  //     width: 150
  // },
  {
    headerName: '物料大类',
    field: 'majorCategory',
    width: 150
  },
  {
    headerName: '物料小类',
    field: 'subCategory',
    width: 150
  },
  {
    headerName: '物料编号',
    field: 'materialCode',
    width: 150
  },
  {
    headerName: '物料名称',
    field: 'materialName',
    width: 150
  },
  {
    headerName: '单位',
    field: 'unit',
    width: 150
  },
  {
    headerName: '等级',
    field: 'grade',
    width: 150
  },
  {
    headerName: "以旧换新",
    field: "oldNewService",
    cellRenderer: {
      template: `
        <a-checkbox v-model="val" disabled></a-checkbox>`,
      setup(props: any) {
        let val = ref()
        val.value = props.params.data.oldNewService == 0 ? false : true
        return {
          val,
        }
      },
    },
    width: 120,
  },
  {
    headerName: '需求出库数量',
    field: 'totalNum',
    width: 150
  },
  {
    headerName: '库存数量',
    field: 'stockNum',
    width: 150
  },
  {
    headerName: '需求时间',
    field: 'requisitionTime',
    width: 150
  },
  {
    headerName: '规格',
    field: 'specification',
    width: 150
  },
]

const tc3 = [
  {
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {
    headerName: '单号',
    field: 'orderNo',
    // pinned: o['fixed'],
    width: 150,
  },
  {
    headerName: '出库类型',
    field: 'outStockType',
    width: 150
  },
  {
    headerName: '公司',
    field: 'companyName',
    width: 150
  },
  {
    headerName: '仓库类型',
    field: 'warehouseTypeName',
    width: 150
  },
  {
    headerName: '仓库名称',
    field: 'warehouseName',
    width: 150
  },
  {
    headerName: '创建人',
    field: 'createName',
    width: 150
  },
  {
    headerName: '创建时间',
    field: 'createTime',
    width: 150
  },
  {
    headerName: '操作',
    field: 'aouts',
    pinned: 'right',
    width: 150,
    cellRenderer: {
      template: `
        <a-button @click="a" type="primary" size="small">打印</a-button>
      `,
      setup(props: any) {
        const a = () => {
          printDatas.value = props.params.data
          post({
            url: 'dwWms/dwIronwareOutStock/getList',
            data: {orderNo: [props.params.data.orderNo]},
            responseType: 'blob'
          }).then((res) => {
            let reader = new FileReader();
            reader.readAsDataURL(res);
            reader.onload = function () {
              let pdfBase64 = reader.result.replace('data:application/pdf;base64,', '');
              printJS({printable: pdfBase64, type: 'pdf', base64: true})
            };
          });
        }
        return {
          a
        }
      }
    }
  }
]

const printDatas: any = ref()
const printDataLists: any = ref()

const selectHandler = () => {
  if (tabsKeys.value == 1) {
    cxYcList()
  } else if (tabsKeys.value == 2) {
    cxCgsList()
  } else if (tabsKeys.value == 3) {
    cxYcList2()
  }
}

const tabsKeys = ref(1)

const tabsChanges = (e: any) => {
  tabsKeys.value = e
  if (e == 1) {
    // 新建调拨单
    toolbarList.value = ['查询', '审核', '删除']
  } else if (e == 2) {
    toolbarList.value = ['查询', '出库']
  } else if (e == 3) {
    toolbarList.value = ['查询', '打印']
  }
}

const cgDcuList = reactive({
  pwDds: '',
  pwDds2: '',
})

const cxCgsList = async () => {
  // isWlNameds,
  // isWlCodeds,
  post({
    url: 'dwWms/dwIronwareOutStock/getWjPendingInfo',
    data: {
      page: fySelet.page,
      size: fySelet.size,
      // firmName: pageData.c,
      // materialCode: pageData.d,
      // materialName: pageData.e,
      infoType: 1,
    }
  }).then((res: any) => {
    gridOption2.value.setRowData(res.data.list)
    tableDataList2.value = res.data.list
    fySelet.total = res.data.total
  })
}

const cxYcList = () => {
  post({
    url: 'dwWms/dwIronwareOutStock/getPage',
    data: {
      page: fySelet2.page,
      size: fySelet2.size,
      companyId: pageData.a == '' ? null : pageData.a,
      warehouseId: pageData.b,
      orderNo: pageData.z,
      // infoType: pageData.f == '' ? null : pageData.f,
    }
  }).then((res: any) => {
    gridOption.value.setRowData(res.data.data)
    tableDataList.value = res.data.data
    fySelet2.total = res.data.total
  })
}

const cgRoutList: any = ref([])

const redersOut = () => {
  if (gridOption2.value.getSelectedRows().length == 0) {
    Message.error('请选择领料单号')
    return
  }
  for (let i = 0; i < gridOption2.value.getSelectedRows().length; i++) {
    for (let j = i + 1; j < gridOption2.value.getSelectedRows().length; j++) {
      if (gridOption2.value.getSelectedRows()[i].materialRequestNo != gridOption2.value.getSelectedRows()[j].materialRequestNo) {
        Message.error('请勾选相同领料单号')
        return
      }
    }
  }
  for (let i = 0; i < gridOption2.value.getSelectedRows().length; i++) {
    if (gridOption2.value.getSelectedRows()[i].oldNewService == 1) {
      Message.warning(`物料名为 ${gridOption2.value.getSelectedRows()[i].materialName} 的单据以旧换新，旧物品退回换新物品!`)
    }
  }
  cgData.value = JSON.parse(JSON.stringify(gridOption2.value.getSelectedRows()))

  cgOut.visible = true
}

const cgOut = reactive({
  visible: false,
  visible2: false,
  title: '领料单出库'
})

const cgHandleOk = async () => {
  cgData.value.forEach((item: any) => {
    item['companyId'] = item.firmId
    item['companyName'] = item.firm
    item['infoType'] = 1
    item['outStockType'] = '领料出库'
    delete item.firmId
    delete item.firm
  })
  const {code, message} = await post({
    url: 'dwWms/dwIronwareOutStock/addOut',
    data: cgData.value
  })
  if (code == 200) {
    cxYcList()
    cxCgsList()
    Message.success('成功')
    return true
  }
  Message.error(message)
  return false
}

const cgColumns: any = [
  {
    dataIndex: 'materialRequestNo',
    key: 'materialRequestNo',
    title: '领料单号',
    width: 150,
  },
  {
    dataIndex: 'firm',
    key: 'firm',
    title: '公司',
    width: 150,
  },
  {
    dataIndex: 'warehouseName',
    key: 'warehouseName',
    title: '仓库名称',
    width: 150,
  },
  {
    dataIndex: 'majorCategory',
    key: 'majorCategory',
    title: '物料大类',
    width: 150,
  },
  {
    dataIndex: 'subCategory',
    key: 'subCategory',
    title: '物料小类',
    width: 150,
  },
  {
    dataIndex: 'materialCode',
    key: 'materialCode',
    title: '物料编号',
    width: 150,
  },
  {
    dataIndex: 'materialName',
    key: 'materialName',
    title: '物料名称',
    width: 150,
  },
  {
    dataIndex: 'unit',
    key: 'unit',
    title: '单位 ',
    width: 150,
  },
  {
    dataIndex: 'grade',
    key: 'grade',
    title: '等级 ',
    width: 150,
  },
  {
    dataIndex: 'requisitionTime',
    key: 'requisitionTime',
    title: '需求时间',
    width: 150,
  },
  {
    dataIndex: 'specification',
    key: 'specification',
    title: '规格 ',
    width: 150,
  },
  {
    dataIndex: 'totalNum',
    key: 'totalNum',
    title: '需求出库数量',
    width: 150,
    fixed: 'right',
  },
  {
    dataIndex: 'stockNum',
    key: 'stockNum',
    title: '库存数量',
    width: 150,
    fixed: 'right',
  },
  {
    dataIndex: 'oldNewNum',
    key: 'oldNewNum',
    slotName: 'oldNewNum',
    title: '以旧换新数量',
    width: 150,
    fixed: 'right',
  },
]

const warehouseChange = ($event: any, record: any) => {
  if ($event != '' || $event != undefined) {
    record['warehouseId'] = Number($event.split('-')[0])
    record['warehouseName'] = $event.split('-')[1]
    return
  }
}

const cadelvs = () => {
  cgData.value = []
  cgOut.visible = false
}

const delSles = () => {
  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk: () => {
      if (tabsKeys.value == 1) {
        post({
          url: 'dwWms/dwIronwareOutStock/delete',
          data: gridOption.value.getSelectedRows().map((res: any) => res.id)
        }).then((res: any) => {
          if (res.code == 200) {
            Message.success('删除成功')
            cxYcList()
          } else (
              Message.error(res.message)
          )
        })
      } else if (tabsKeys.value == 3) {
        post({
          url: 'dwWms/dwIronwareOutStock/delete',
          data: gridOption3.value.getSelectedRows().map((res: any) => res.id)
        }).then((res: any) => {
          if (res.code == 200) {
            Message.success('删除成功')
            cxYcList2()
          } else (
              Message.error(res.message)
          )
        })
      }
    },
  })
}

const audits = () => {
  if (tabsKeys.value == 1) {
    Modal.confirm({
      title: '系统提示',
      content: '确认是否审核选中的数据?',
      onOk: () => {
        post({
          url: 'dwWms/dwIronwareOutStock/audit',
          data: {
            infoState: 2,
            infos: gridOption.value.getSelectedRows().map((res: any) => {
              return {id: res.id}
            })
          }
        }).then((res: any) => {
          if (res.code == 200) {
            Message.success('成功')
            cxYcList()
          } else (
              Message.error(res.message)
          )
        })
      },
    })
  } else if (tabsKeys.value == 3) {
    Modal.confirm({
      title: '系统提示',
      content: '确认是否审核选中的数据?',
      onOk: () => {
        post({
          url: 'dwWms/dwIronwareOutStock/audit',
          data: {
            infoState: 2,
            infos: gridOption3.value.getSelectedRows().map((res: any) => {
              return {id: res.id}
            })
          }
        }).then((res: any) => {
          if (res.code == 200) {
            Message.success('成功')
            cxYcList2()
          } else (
              Message.error(res.message)
          )
        })
      },
    })
  }
}

const cgData: any = ref([])

const adddbs = () => {
  dbPageDate.showAdd = true
}

const dbPageDate = reactive({
  showAdd: false,
  showAdd2: false,
  titles: '新建调拨单'
})

const formRef = ref()

const sideOk = async () => {
  if (wlListArray.value.length == 0) {
    Message.warning({
      content: "请新增至少一条物料信息",
      duration: 5000,
    });
    return
  }
  for (let i = 0; i < wlListArray.value.length; i++) {
    if (wlListArray.value[i].totalNum == 0) {
      Message.error('数量必须大于0')
      return
    }
    if (wlListArray.value[i].grade == '' || wlListArray.value[i].grade == null || wlListArray.value[i].grade == undefined) {
      Message.error('等级必填')
      return
    }
  }

  formRef.value?.validate().then((err: any) => {
    if (!err) {
      wlListArray.value.forEach((item: any) => {
        item['companyId'] = searchData.fhFirmId
        item['companyName'] = searchData.fhFirm
        item['inCompanyId'] = searchData.shFirmId
        item['inCompanyName'] = searchData.shFirm
        item['inWarehouseTypeName'] = searchData.shWhType
        item['warehouseId'] = Number(searchData.fhWh.split('-')[0])
        item['warehouseName'] = searchData.fhWh.split('-')[1]
        item['inWarehouseId'] = Number(searchData.shWh.split('-')[0])
        item['inWarehouseName'] = searchData.shWh.split('-')[1]
        item['infoType'] = 2
        item['outStockType'] = '调拨单出库'
        item['warehouseTypeName'] = '五金仓'
      })
      post({
        url: 'dwWms/dwIronwareOutStock/addOut',
        data: wlListArray.value
      }).then(({code, message}) => {
        if (code == 200) {
          cxYcList()
          cxCgsList()
          Message.success('成功')
          for (let i in searchData) {
            searchData[i] = ''
          }
          wlListArray.value = []
          dbPageDate.showAdd = false
        } else {
          Message.error(message)
        }
      })
    }
  })
}

const sideNo = () => {
  for (let i in searchData) {
    searchData[i] = ''
  }
  wlListArray.value = []
  dbPageDate.showAdd = false
}

const searchData: any = reactive({
  fhFirm: '',
  fhFirmId: null,
  fhWh: '',
  shFirm: '',
  shFirmId: null,
  shWhType: '',
  shWh: '',
  infoType: null
})

const configCascader = ref<{}>({
  corporateWidth: '15rem', //公司宽度
  sectorWidth: '180px', //部门宽度
  corporateRquired: true, //公司是否必填
  sectorRquired: false, //部门是否必填
  size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
  corporateName: '发货公司', //公司label
  sectorName: '选择部门', //部门label
  cascaderShow: 'sector', //配置部门不显示
})
const configCascader2 = ref<{}>({
  corporateWidth: '15rem', //公司宽度
  sectorWidth: '180px', //部门宽度
  corporateRquired: true, //公司是否必填
  sectorRquired: false, //部门是否必填
  size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
  corporateName: '收货公司', //公司label
  sectorName: '选择部门', //部门label
  cascaderShow: 'sector', //配置部门不显示
})
const whService = new WHService()
const fhWhList: any = whService.whList
const changeCascader = (data: any) => {
  const {corporateId, sectorId, sectorLabel, corporateLabel} = data
  searchData.fhWh = ""
  searchData.fhFirmId = corporateId
  searchData.fhFirm = corporateLabel
  whService.getWarhouseListByFirmId(corporateId, '五金仓')
}
const changeCascader2 = (data: any) => {
  const {corporateId, sectorId, sectorLabel, corporateLabel} = data
  searchData.shWh = ""
  searchData.shFirmId = corporateId
  searchData.shFirm = corporateLabel
  whService.getWarhouseListByFirmId(corporateId, '五金仓')
}
const whTypeList: any = ref([])

const whService2 = new WHService()
const shWhList: any = whService2.whList
const whTypeChanges = (e: any) => {
  whService2.getWarhouseListByFirmId(searchData.shFirmId, e)
}

const wlListArray: any = ref([])

const tableColumnsWl: any = [
  {
    title: "物料大类",
    key: "majorCategory",
    dataIndex: "majorCategory",
    width: 150,
    slotName: 'majorCategory',
  },
  {
    title: "物料小类",
    key: "subCategory",
    dataIndex: "subCategory",
    width: 150,
    slotName: 'subCategory',
  },
  {
    title: "物料编号",
    key: "materialCode",
    dataIndex: "materialCode",
    width: 150,
    slotName: 'materialCode'
  },
  {
    title: "物料名称",
    key: "materialName",
    dataIndex: "materialName",
    width: 150,
    slotName: 'materialName'
  },
  {
    dataIndex: 'grade',
    key: 'grade',
    title: '等级',
    width: 150,
    slotName: 'grade'
  },
  {
    title: "数量",
    key: "totalNum",
    dataIndex: "totalNum",
    width: 150,
    slotName: 'totalNum'
  },
  {
    title: "单位",
    key: "unit",
    dataIndex: "unit",
    width: 150,

  },
  {
    dataIndex: 'specification',
    key: 'specification',
    title: '规格 ',
    width: 150,
  },
  {
    dataIndex: 'totalNum2',
    key: 'totalNum2',
    slotName: 'totalNum2',
    title: '库存数量',
    width: 150,
  },
]
let typeIds = 0
const addLine = () => {
  if (searchData.fhWh == '' || searchData.fhFirm == '') {
    Message.error('请先选择发货公司仓库')
    return
  }
  wlListArray.value.push({
    typeIds: typeIds++,
    majorCategory: '',
    subCategory: '',
    materialCode: '',
    unit: '',
    materialName: '',
    totalNum: 0
  })
}

const selectedRowKeysWl: any = ref([])

const delLine = () => {

  if (selectedRowKeysWl.value.length === 0) {
    Message.error({
      content: '请先勾选',
      duration: 5000
    })
    return
  }

  wlListArray.value = wlListArray.value.filter(function (o: any) {
    return selectedRowKeysWl.value.indexOf(o["typeIds"]) === -1
  })

}

const wlPageDatas: any = reactive({
  wlListL: [],
  wlListS: [],
  wlList: []
})

const focusSel = () => {
  post({
    url: "dwPurchase/MaterialBigClass/getFieldValue",
    data: {"bigClassName": "", deleteState: 0}
  }).then(({data, code}: any) => {
    if (code === 200) {
      wlPageDatas.wlListL = data;
    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}
const focusSel1 = (e: any) => {
  if (e.majorCategory == '') {
    Message.error('请先选择物料大类')
    return
  }
  post({
    url: "dwPurchase/MaterialSubClass/getFieldValue",
    data: {"bigClassName": e.majorCategory}
  }).then(({data, code}: any) => {
    if (code === 200) {
      wlPageDatas.wlListS = data;
    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}
const focusSel2 = (val: any) => {
  post({
    url: "dwPurchase/MaterialInfo/getFieldValueWms",
    data: val
  }).then(({data, code}: any) => {
    if (code === 200) {
      wlPageDatas.wlList = data;
    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}

const cxKcsl = async (val: any, val2: any) => {
  const res = await post({
    url: 'dwWms/dwIronwareStockSummary/getGoodsStockNum',
    data: {
      materialCode: val,
      grade: val2,
      warehouseId: Number(searchData.fhWh.split('-')[0]),
    }
  })
  if (res.code == 200) {
    return res.data.totalNum
  }
}

const changeWl = (record: any, val: any) => {
  if (val == '') {
    record['materialName'] = ''
    record['materialCode'] = ''
    record['specification'] = ''
    record['majorCategory'] = ''
    record['subCategory'] = ''
    record['unit'] = ''
    return
  }
  let list2 = wlListArray.value.filter(function (o: any) {
    return (o['materialName'] == record['materialName'])
  })
  if (list2.length > 1) {
    record['materialName'] = ''
    record['materialCode'] = ''
    record['specification'] = ''
    record['majorCategory'] = ''
    record['subCategory'] = ''
    record['unit'] = ''
    Message.warning({
      content: '请不要重复选择物料！',
      duration: 5000,
    })
    return
  }
  let list = wlPageDatas.wlList.filter(function (o: any) {
    return o['materialName'] == val
  })
  if (list.length > 0) {
    record['materialCode'] = list[0]['materialCode']
    record['unit'] = list[0]['unit']
    record['specification'] = list[0]['specification']
    record['majorCategory'] = list[0]['materialL']
    record['subCategory'] = list[0]['materialS']
    cxKcsl(val, record['grade']).then((res: any) => {
      record['totalNum2'] = res
    })
  }
}
const changeWl2 = (record: any, val: any) => {
  if (val == '') {
    record['materialName'] = ''
    record['materialCode'] = ''
    record['specification'] = ''
    record['majorCategory'] = ''
    record['subCategory'] = ''
    record['unit'] = ''
    return
  }
  let list2 = wlListArray.value.filter(function (o: any) {
    return (o['materialCode'] == record['materialCode'])
  })
  if (list2.length > 1) {
    record['materialName'] = ''
    record['materialCode'] = ''
    record['unit'] = ''
    record['specification'] = ''
    record['majorCategory'] = ''
    record['subCategory'] = ''
    Message.warning({
      content: '请不要重复选择物料！',
      duration: 5000,
    })
    return
  }
  let list = wlPageDatas.wlList.filter(function (o: any) {
    return o['materialCode'] == val
  })
  if (list.length > 0) {
    record['materialName'] = list[0]['materialName']
    record['unit'] = list[0]['unit']
    record['specification'] = list[0]['specification']
    record['majorCategory'] = list[0]['materialL']
    record['subCategory'] = list[0]['materialS']
    cxKcsl(val, record['grade']).then((res: any) => {
      record['totalNum2'] = res
    })
  }
}
const qkChanges = (record: any) => {
  record['materialCode'] = ''
  record['unit'] = ''
  record['materialName'] = ''
}

const gradrList: any = ref([])

const gradeChange = (e: any) => {
  if (e.materialName == '' || e.materialCode == '') {
    Message.error('请先选择物料')
    return
  }
  post({
    url: 'dict/dictTypeDetail/getListByMap',
    data: {
      codeType: 36,
      detailName: ''
    }
  }).then(({data, code}: any) => {
    if (code === 200) {
      gradrList.value = data;
    }
  })
}

const totalNum2: any = ref()

const grachanges = (e: any) => {
  cxKcsl(e['materialCode'], e['grade']).then((res: any) => {
    e['totalNum2'] = res
  })
}

const configCascader3 = ref<{}>({
  corporateWidth: '200px', //公司宽度
  sectorWidth: '180px', //部门宽度
  corporateRquired: false, //公司是否必填
  sectorRquired: false, //部门是否必填
  size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
  corporateName: '选择公司', //公司label
  sectorName: '选择部门', //部门label
  cascaderShow: 'sector', //配置部门不显示
})
const whService3 = new WHService()
const fhWhList3: any = whService3.whList
const changeCascader3 = (data: any) => {
  const {corporateId, sectorId, sectorLabel, corporateLabel} = data
  pageData.b = ""
  pageData.a = corporateId
  whService3.getWarhouseListByFirmId(corporateId, '五金仓')
}

const cgHandleOk2 = async () => {
  const {code, message} = await post({
    url: 'dwWms/dwIronwareOutStock/updateById',
    data: cgData2.value[0]
  })
  if (code == 200) {
    cxYcList()
    cxCgsList()
    Message.success('成功')
    return true
  }
  Message.error(message)
  return false
}

const cadelvs2 = () => {
  cgData2.value = []
  cgOut.visible2 = false
}

const cgData2: any = ref([])

const cgColumns2: any = [
  {
    dataIndex: 'orderNo',
    key: 'orderNo',
    title: '单号',
    width: 150,
  },
  {
    dataIndex: 'outStockType',
    key: 'outStockType',
    title: '出库类型',
    width: 150,
  },
  {
    dataIndex: 'companyName',
    key: 'companyName',
    title: '公司',
    width: 150,
  },
  {
    dataIndex: 'warehouseTypeName',
    key: 'warehouseTypeName',
    title: '仓库类别',
    width: 150,
  },
  {
    dataIndex: 'warehouseName',
    key: 'warehouseName',
    title: '仓库',
    width: 150,
  },
  {
    dataIndex: 'materialRequestNo',
    key: 'materialRequestNo',
    title: '五金领料单号',
    width: 150,
  },
  {
    dataIndex: 'inWarehouseTypeName',
    key: 'inWarehouseTypeName',
    title: '收货仓库类型',
    width: 150,
  },
  {
    dataIndex: 'inCompanyName',
    key: 'inCompanyName',
    title: '收货公司 ',
    width: 150,
  },
  {
    dataIndex: 'inWarehouseName',
    key: 'inWarehouseName',
    title: '收货仓库 ',
    width: 150,
  },
  {
    dataIndex: 'majorCategory',
    key: 'majorCategory',
    title: '物料大类',
    width: 150,
  },
  {
    dataIndex: 'subCategory',
    key: 'subCategory',
    title: '物料小类',
    width: 150,
  },
  {
    dataIndex: 'materialCode',
    key: 'materialCode',
    title: '物料编号',
    width: 150,
  },
  {
    dataIndex: 'materialName',
    key: 'materialName',
    title: '物料名称',
    width: 150,
  },
  {
    dataIndex: 'specification',
    key: 'specification',
    title: '规格',
    width: 150,
  },
  {
    dataIndex: 'unit',
    key: 'unit',
    title: '单位',
    width: 150,
  },
  {
    dataIndex: 'totalNum',
    key: 'totalNum',
    title: '出库数量',
    slotName: 'totalNum',
    width: 150,
    fixed: 'right',
  },
]

const redersOut2 = (data: any) => {
  cgData2.value = JSON.parse(JSON.stringify([data]))
  cgOut.visible2 = true
}

const addList = () => {
  dbPageDate.showAdd2 = true
}

const cgData3: any = ref([])

const delLine2 = (e: any) => {
  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk: () => {
      cgData4.value = cgData4.value.filter((val: any) => {
        return val != e
      })
    },
  })
}
const cxYcList2 = () => {
  post({
    url: 'dwWms/dwIronwareOutStock/getPrintList',
    data: {
      page: fySelet3.page,
      size: fySelet3.size,
      orderNo: pageData.f,
      // companyId: pageData.a == '' ? null : pageData.a,
      // warehouseId: pageData.b,
      // orderNo: pageData.z,
      // infoType: pageData.f == '' ? 3 : pageData.f,
    }
  }).then((res: any) => {
    gridOption3.value.setRowData(res.data.data)
    tableDataList3.value = res.data.data
    fySelet3.total = res.data.total
  })
}

const formRef2 = ref()

const sideOk2 = () => {
  if (cgData4.value.length == 0) {
    Message.error('请选择采购单')
    return
  }
  formRef2.value?.validate().then((err: any) => {
    if (!err) {
      cgData4.value.forEach((item: any) => {
        item['companyId'] = searchData.fhFirmId
        item['companyName'] = searchData.fhFirm
        item['warehouseId'] = Number(searchData.fhWh.split('-')[0])
        item['warehouseName'] = searchData.fhWh.split('-')[1]
        item['infoType'] = searchData.infoType
      })
      post({
        url: 'dwWms/dwIronwareOutStock/addOut',
        data: cgData4.value
      }).then(({code, message}) => {
        if (code == 200) {
          cxYcList2()
          Message.success('成功')
          for (let i in searchData) {
            searchData[i] = ''
          }
          cgData4.value = []
          dbPageDate.showAdd2 = false
        } else {
          Message.error(message)
        }
      })
    }
  })
}
const sideNo2 = () => {
  fhWhList.value = []
  cgData4.value = []
  pageData.g = ''
  dbPageDate.showAdd2 = false
}

const addLine2 = () => {
  if (searchData.fhWh == '' || searchData.fhWh == undefined) {
    Message.error('请先选择仓库')
    return
  }
  visibleYl.value = true
}
const cgColumns4: any = [
  {
    dataIndex: 'purchaseOrderNo',
    key: 'purchaseOrderNo',
    title: '采购单号',
    width: 150,
  },
  {
    dataIndex: 'supplierName',
    key: 'supplierName',
    title: '供应商名称',
    width: 150,
  },
  {
    dataIndex: 'majorCategory',
    key: 'majorCategory',
    title: '物料大类',
    width: 150,
  },
  {
    dataIndex: 'subCategory',
    key: 'subCategory',
    title: '物料小类',
    width: 150,
  },
  {
    dataIndex: 'materialCode',
    key: 'materialCode',
    title: '物料编号',
    width: 150,
  },
  {
    dataIndex: 'materialName',
    key: 'materialName',
    title: '物料名称',
    width: 150,
  },
  {
    dataIndex: 'specification',
    key: 'specification',
    title: '规格',
    width: 150,
  },
  {
    dataIndex: 'unit',
    key: 'unit',
    title: '单位 ',
    width: 150,
  },
  {
    dataIndex: 'grade',
    key: 'grade',
    title: '等级 ',
    width: 150,
  },
  {
    dataIndex: 'stockNum',
    key: 'stockNum',
    title: '库存数量 ',
    width: 150,
  },
  {
    dataIndex: 'totalNum2',
    key: 'totalNum2',
    title: '已入库数量',
    slotName: 'totalNum2',
    width: 150,
    fixed: 'right',
  },
  {
    dataIndex: 'totalNum',
    key: 'totalNum',
    title: '待出库数量',
    slotName: 'totalNum',
    width: 150,
    fixed: 'right',
  },
  {
    dataIndex: 'acFighs',
    key: 'acFighs',
    title: '操作',
    slotName: 'acFighs',
    width: 150,
    fixed: 'right',
  },
]
const cgData4: any = ref([])

const visibleYl = ref(false)
const isLyCodeds: any = ref('')
const isLyNameds: any = ref('')
const selectedRowKeys2: any = ref([])
const wlListXqs: any = ref([])

const handleOks = () => {
  if (selectedRowKeys2.value.length == 0) {
    Message.error('请勾选数据')
    return false
  }
  let islistArray: any = []
  for (let i = 0; i < wlListXqs.value.length; i++) {
    if (selectedRowKeys2.value.includes(wlListXqs.value[i].typeLesIds)) {
      islistArray.push(wlListXqs.value[i])
    }
  }
  if (cgData4.value.length != 0) {
    let wlAarray: any = []
    for (let i = 0; i < islistArray.length; i++) {
      wlAarray.push(islistArray[i].materialCode)
    }
    for (let i = 0; i < cgData4.value.length; i++) {
      if (wlAarray.includes(cgData4.value[i].materialCode)) {
        Message.error('请勿勾选相同物料')
        return false
      }
    }
    for (let i = 0; i < islistArray.length; i++) {
      if (cgData4.value[0].purchaseOrderNo != islistArray[i].purchaseOrderNo) {
        Message.error('请勾选相同采购单')
        return false
      }
    }
  }
  cgData4.value.push(...islistArray)
  isLyCodeds.value = ''
  isLyNameds.value = ''
  wlListXqs.value = []
  selectedRowKeys2.value = []
  visibleYl.value = false
  return true
}
let typeLesIds = 0;
const cxCgsLists = async () => {
  const res: any = await post({
    url: 'dwWms/dwIronwareInStock/getPageByInStockRecord',
    data: {
      page: fySelet4.page,
      size: fySelet4.size,
      warehouseId: Number(searchData.fhWh.split('-')[0]),
      materialCode: isLyCodeds.value,
      materialName: isLyNameds.value,
    }
  })
  if (res.code == 200) {
    wlListXqs.value = res.data.list
    wlListXqs.value.forEach((res: any) => {
      res['typeLesIds'] = typeLesIds++
      res['totalNum2'] = res.totalNum
    })
    fySelet4.total = res.data.total
  }
}
const handleCancels = () => {
  isLyCodeds.value = ''
  isLyNameds.value = ''
  wlListXqs.value = []
  selectedRowKeys2.value = []
  visibleYl.value = false
}

const cgColumns5: any = [
  {
    dataIndex: 'purchaseOrderNo',
    key: 'purchaseOrderNo',
    title: '采购单号',
    width: 150,
  },
  {
    dataIndex: 'supplierName',
    key: 'supplierName',
    title: '供应商名称',
    width: 150,
  },
  {
    dataIndex: 'majorCategory',
    key: 'majorCategory',
    title: '物料大类',
    width: 150,
  },
  {
    dataIndex: 'subCategory',
    key: 'subCategory',
    title: '物料小类',
    width: 150,
  },
  {
    dataIndex: 'materialCode',
    key: 'materialCode',
    title: '物料编号',
    width: 150,
  },
  {
    dataIndex: 'materialName',
    key: 'materialName',
    title: '物料名称',
    width: 150,
  },
  {
    dataIndex: 'specification',
    key: 'specification',
    title: '规格',
    width: 150,
  },
  {
    dataIndex: 'unit',
    key: 'unit',
    title: '单位 ',
    width: 150,
  },
  {
    dataIndex: 'grade',
    key: 'grade',
    title: '等级 ',
    width: 150,
  },
  {
    dataIndex: 'stockNum',
    key: 'stockNum',
    title: '库存数量 ',
    width: 150,
  },
  {
    dataIndex: 'totalNum',
    key: 'totalNum',
    title: '已入库数量',
    slotName: 'totalNum',
    width: 150,
  },
]

const visibleYl2 = ref(false)


const handleOks2 = async () => {
  await printJS({
    printable: 'wjDyings',
    type: 'html',
    font_size: '',
    targetStyles: ['*'],
  })
  return true
}

const handleCancels2 = () => {
  visibleYl2.value = false
}

const dyBoufeis = () => {
  if (tableDataList.value.length > 1 || tableDataList.value.length == 0) {
    Message.error('数据有误')
    return false
  }
  visibleYl2.value = true
}

const NumChange = (record: any) => {
  if (record.oldNewNum > record.totalNum) {
    record.oldNewNum == null
    Message.warning('不能超过出库数量!')
    return false
  }
}

const numEnter = (record: any) => {
  if (record.oldNewService == 0) {
    pageData.isEdit = true
  } else {
    pageData.isEdit = false
  }
}

function printRef() {
  if (gridOption3.value.getSelectedRows().length == 0) {
    Message.error('请勾选数据!')
    return
  }
  let orderNoList = gridOption3.value.getSelectedRows().map((o: any) => {
    return {
      orderNo: o.orderNo
    }
  })
  post({
    url: 'dwWms/dwIronwareOutStock/getList',
    data: orderNoList,
    responseType: 'blob'
  }).then((res) => {
    let reader = new FileReader();
    reader.readAsDataURL(res);
    reader.onload = function () {
      let pdfBase64 = reader.result.replace('data:application/pdf;base64,', '');
      printJS({printable: pdfBase64, type: 'pdf', base64: true})
    };
  });
}

</script>

<style scoped lang="less">
:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

.cgisDatas {
  width: 50%;
  display: flex;
  justify-content: space-between;
}

.isTable {
  width: 100%;
  height: 70%;
  margin: 0 auto;
  border: 1.2px solid #000;
  text-align: center;
  border-collapse: collapse;

  tr {
    height: 10px;
  }

  td {
    border: 1.2px solid #000;
  }

  th {
    border: 1.2px solid #000;
  }
}

.No1 {
  width: 100%;
  height: 30%;
  margin-bottom: 10px;

  .No1-1 {
    width: 100%;
    font-size: 20px;
    font-weight: 550;
    text-align: center;
  }

  .No1-2 {
    width: 100%;
    font-size: 20px;
    font-weight: 500;
    text-align: center;
  }

  .No1-3 {
    width: 40%;
    display: flex;
    justify-content: space-between;
  }

  .No1-4 {
    width: 72%;
    display: flex;
    justify-content: space-between;
  }

  .No1-5 {
    width: 100%;
  }
}
</style>